package com.kaifamiao.service;

import com.kaifamiao.dao.CustomerDao;
import com.kaifamiao.entity.Customer;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;

import java.time.LocalDate;
import java.util.List;

public class CustomerService {

    private CustomerDao customerDao = new CustomerDao();

    public String encrypt(final String source,final String salt){
        // 首先对原始密码进行加密
        String encrypted = DigestUtils.sha1Hex(source);
        StringBuilder builder = new StringBuilder( encrypted );
        // 在加密后的字符序列指定位置插入盐值
        builder.insert( 20, salt );
        // 获得插入盐值后的字符串
        String inserted = builder.toString();
        // 对插入盐值后的字符串进行加密
        return DigestUtils.sha1Hex( inserted );
    }

    public boolean save(Customer c){
        final String salt = RandomStringUtils.randomAlphanumeric(5);
        // 设置盐值
        c.setSalt(salt);
        String passsword = c.getPassword();
        passsword = encrypt(passsword, salt);
        // 设置加密后的密码
        c.setPassword( passsword );
        // 设置注册日期
        c.setRegistrationDate( LocalDate.now() );
        // 调用DAO中的方法完成保存操作
        return customerDao.save( c );
    }

    public Customer load(String username) {
        return customerDao.find(username);
    }

    public Customer load(Integer id) {
        return customerDao.find(id);
    }

    public List<Customer> loadAll(){
        return customerDao.findAll();
    }

    public boolean update(Customer c){
        return customerDao.update(c);
    }

    public boolean delete(Integer id) {
        return customerDao.remove(id);
    }

}
